package com.jeesite.modules.ic.service.wx;

import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
@Slf4j
public class FileService {

    @Value("${file.baseDir}")
    private String baseDir;

    @Value("${pic.baseUrl}")
    private String houtaiPicBaseUrl;

    public String onLinePicSaveServer(String urlLine){
        String month = DateUtils.getDate("yyyy-MM");
        try{
            String picName= IdGen.uuid();
            String dirUrl = baseDir+"/userfiles/system/pic/"+month+"/";
            if(new File(dirUrl).exists()){
                new File(dirUrl).createNewFile();
            }
            String destFileName = dirUrl+ picName+".jpg";
            URL url = new URL(urlLine);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            httpURLConnection.setRequestMethod("GET");

            // 连接网络并获取响应码
            int responseCode = httpURLConnection.getResponseCode();

            // 检查响应码是否为HTTP_OK
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, new File(destFileName));

                inputStream.close();
                String lineUrl = houtaiPicBaseUrl+"/js/userfiles/system/pic/"+month +"/" + picName + ".jpg";
                log.info("图片已保存到: " + destFileName);
                return lineUrl;
            }
        }catch (Exception e){
            log.error("图片上传失败：",e);
        }
        return null;
    }
}
